package com.oc.mba.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.oc.mba.service.PaymentService;
import com.oc.mba.util.CommLog;
import com.oc.mba.util.MD5;
import com.oc.mba.util.SpringUtil;

public class PayNotifyController extends BaseController {

	private static final CommLog logger = new CommLog(PayNotifyController.class);
	//开发者ID
	public static String U_ID = "1880577";
	//channelID、APP_KEY
	public static String APP_KEY = "834266553";
	//密钥
	public static String SECRET_KEY = "e1ed225be8f2b9ce";
	
	final String ORDERID_KEY = "order_id";
	final String ORDERCOST_KEY = "cost";
	final String APPKEY_KEY = "appkey";
	final String CREATETIME_KEY = "create_time";
		
	PayNotifyController() {
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
	}
	/**
	 * 分发逻辑
	 * @param request 请求
	 * @param response 响应
	 * @throws Exception 异常
	 */
	public void dispatch(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info("PayNotifyController progress....");
		String time = request.getParameter("time");
		String sign = request.getParameter("sign");
		//验证签名 1接收成功，0接收失败
		int ErrorCode = 0;
		String errorDesc = "主动通知响应处理失败";
		if (sign.equals(MD5.encryptHex(U_ID + time))) {
			ErrorCode = 1;
			errorDesc = errorDesc.replace("失败", "成功");
			//签名正确，在这里处理业务
			doBusiness(request);
		}
		
		String result = "<response><ErrorCode>"+ErrorCode+"</ErrorCode><ErrorDesc>"+errorDesc+"</ErrorDesc></response>";
		resultXml(response, result);
		logger.info("PayNotifyController result=" + result);
	}

	private void doBusiness(HttpServletRequest request) throws IOException {
		//解析参数并处理，内容如下
		logger.info("=============================");
		logger.info("Gfan notify order post request");
		logger.info("=============================");
        BufferedReader reader = new BufferedReader(new   InputStreamReader(request.getInputStream()));
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        while ( (line=reader.readLine()) != null ) {
            stringBuilder.append(line).append("\n");
        }

        String retval = stringBuilder.toString();
        logger.info(retval);
        logger.info("=============================");
        logger.info("Gfan notify order post request ends");
        logger.info("=============================");
        String orderID = "";
        try {
			orderID = extractProperty(retval, ORDERID_KEY);
			String cost = extractProperty(retval, ORDERCOST_KEY);
	        String appKey = extractProperty(retval, APPKEY_KEY);
	        String createTime = extractProperty(retval, CREATETIME_KEY);
	        PaymentService paymentService = (PaymentService) SpringUtil.getBean("paymentServiceImpl");
	        paymentService.payOrder(orderID, cost);
	        logger.info("order pay success. orderID=" + orderID);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("order pay failure. orderID=" + orderID);
		}
	}
	
	private String extractProperty(String response, String key) throws Exception {
		if (response.indexOf(key) != -1) {
			int startPos = response.indexOf("<" + key + ">") + 2 + key.length();
			int endPos = response.indexOf("</" + key + ">");
			return response.substring(startPos, endPos);
		}
		throw new Exception("response does not contains key [" + key+ "]!");
	}
}
